package user_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type BindEmailRequest struct {
	Email    string  `json:"email" binding:"required,email" msg:"邮箱不正确"`
	Code     *string `json:"code"`
	Password string  `json:"password"`
}

func (UserApi) UserBindEmailView(c *gin.Context) {
	// 第一次输入邮箱, 后台发送验证码
	var cr BindEmailRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		http.FailWithError(err, &cr, c)
		return
	}
	session := sessions.Default(c)
	if cr.Code == nil {
		code := utils.RandNumber()
		// 发送邮箱
		session.Set("bind_code", code)
		err := session.Save()
		if err != nil {
			common.Log.Error(err)
			http.FailWithMessage("session 保存失败", c)
			return
		}
		err = utils.NewCode().Send(cr.Email, "你的验证码是 "+code)
		if err != nil {
			common.Log.Error(err)
			http.FailWithMessage("验证码发送失败", c)
			return
		}
		http.IsOkWithMessage("验证法已发送，请查收", c)
		return
	}
	// 校验验证码
	code := session.Get("bind_code")
	if code != *cr.Code {
		http.FailWithMessage("验证码错误", c)
		return
	}
	if cr.Password == "" {
		http.FailWithMessage("请输入用户密码", c)
		return
	}
	// 获取 token 用户信息
	claims, _ := c.Get("user")
	user := claims.(*utils.UserClaims)
	// 第二次, 用户输入邮箱, 验证码, 密码, 完成绑定
	userInfo := new(models.UserModel)
	err := common.DB.Take(&userInfo, user.UserID).Error
	if err != nil {
		http.IsOkWithMessage("用户不存在", c)
		return
	}
	hashPwd, _ := utils.HashPwd(cr.Password)
	err = common.DB.Model(&userInfo).Updates(map[string]any{
		"email":    cr.Email,
		"password": hashPwd,
	}).Error
	if err != nil {
		common.Log.Error(err)
		http.IsOkWithMessage("用户不存在", c)
		return
	}
	http.IsOkWithMessage("邮箱绑定成功", c)
}
